<template>
	<!-- <custom-navigation-bar title=""></custom-navigation-bar> -->
	<view class="main">
		<image class="top" src="/static/index.png"></image>
		<!-- 顶部区域与轮播图 -->
		<view class="top_1">
			<image class="address_1" src="/static/ic_dizhi@3x.png"></image>
			<view class="address_2" @click="bangXiaoQu()">{{district}}</view>
			<image class="address_3" src="/static/ic_xiala@3x.png"></image>
			<image class="address_5" src="/static/ic_xiaoxi@3x.png"></image>
			<image class="address_4" src="/static/ic_kefu@3x.png"></image>
			<view style="width: 100%;float: left;height: 30rpx;"></view>
			<view class="swiper_bg">
				<swiper class="swiper" circular :indicator-dots="indicatorDots" :autoplay="autoplay"
					:interval="interval" :duration="duration">
					<swiper-item v-for="(item,index) in swiper" :key="index" @click="goPage(item)">
						<image class="banner" :src="item.img_url"></image>
					</swiper-item> 
				</swiper>
			</view>
		</view>
		<!-- 搜索 -->
		<view class="ft_1 search_0">
			<input class="search_1" placeholder="请输入商品、机构名称查询" v-model="homeQuery" />
			<view class="search_btn" @click="goodsList">
				<image class="search_0_1" src="/static/ic_home_search@3x.png"></image>
				<view class="search_0_2" >搜索</view>
			</view>
		</view>
		<!-- 服务模块 -->
		<view class="ft_1 menu_0">
			<view class="menu_0_ttt" v-for="menu in menus" :key="menu.id">
				<view class="menu_0_0_1" @click="toMenu(menu.url)">
					<image :src="menu.imgUrl" class="menu_0_1"></image>
				</view>
				<view class="menu_0_2">
					{{menu.name}}
				</view>
			</view>
		</view>
		<!-- 活动推荐展示 -->
<!-- 		<view class="ft_1 items">
			<view class="items_1">
				<view class="items_2"></view>
				<view class="items_3">
					热门活动区<view class="more">更多<image src="/static/gengduo@3x(1).png" class="more_1"></image>
					</view>
				</view>
				<view class="items_4" v-for="product in products" :key="product.id">
					<view class="items_5">
						<image class="items_6" :src="product.url"></image>
						<view class="items_7">
							<view class="items_8">
								团购
							</view>
							<view class="items_9">
								距离您{{product.distance}}米
							</view>
						</view>
					</view>
					<view class="items_10">
						{{product.name}}
					</view>
					<view class="items_11">
						好评率{{product.haoping}}|已购买{{product.nums}}+
					</view>
					<view class="items_12">
						<view class="items_13">&yen;{{product.price}}</view>
						<view class="items_14">&yen;{{product.p1}}</view>
						<view class="items_15">
							{{product.zhekou}}折
						</view>
					</view>
					<view class="items_16">
						全市最低买贵3倍赔偿
					</view>
				</view>
			</view>
		</view> -->
		<view class="ft_1 items" style="height: 380rpx;">
			<view class="items_2"></view>
			<view class="items_3" >
				爆单区<view class="more" @click="moreGoods()" >更多<image src="/static/gengduo@3x(1).png" class="more_1"></image>
				</view>
			</view>
			<swiper class="swiper" circular :indicator-dots="false" :autoplay="autoplay"
				:interval="3000" :duration="1000" >
				<swiper-item v-for="(item,index) in goods" :key="index">
					<view class="items_4" v-for="service in item" :key="service.id" @click="detail(service)">
						<view class="items_5">
							<image class="items_6" :src="service.thumbnail"></image>
							<view class="items_7">
								<view class="items_8">
									团购
								</view>
								<view class="items_9">
									<image class="shop_item10" src="/static/dingwei001.png" style="margin-top: 7rpx;"></image>{{service.juLi}}
								</view>
							</view>
						</view>
						<view class="items_10">
							{{service.name}}
						</view>
						<view class="items_11">
							<view v-for="(i,index) in 5" style="float: left;" :key="index">
								<image v-if="service.score>=i" src="../../static/ic_xing@3x(1).png" style="width: 20rpx;height: 20rpx"></image>
								<image v-if="service.score>=i-0.5&&service.score<i" src="../../static/ic_xing2@3x.png" style="width: 20rpx;height: 20rpx"></image>
								<image v-if="service.score>i-1&&service.score<i-0.5" src="../../static/ic_xing3@3x.png" style="width: 20rpx;height: 20rpx"></image>
							</view> 
							<label style="font-size: 24rpx;">{{service.score}}分</label>
						</view>   
						
						<view class="items_16" style="float: left;margin-left: 20rpx;">
							您有{{service.buyNum}}位邻居已下单
						</view>
						
						<view v-if="service.isBook==1" class="items_16" style="float: left;margin-left: 20rpx;border: none;color: #9D9D9D;text-align: center;font-size: 20rpx;">
							需要预约&nbsp;|&nbsp;交易保障
						</view>
						<view v-if="service.isBook==0" class="items_16" style="float: left;margin-left: 20rpx;border: none;color: #9D9D9D;text-align: center;font-size: 20rpx;">
							无需预约&nbsp;|&nbsp;交易保障
						</view>
						
						<view class="items_12" style="float: left;margin-left: 25rpx;line-height: 30rpx;">
							<lable class="items_13">&yen;{{service.price}}</lable>
							<lable class="items_14">&yen;{{service.originPrice}}</lable>
							<lable class="items_15">
								{{service.zheKou}}
							</lable>
						</view> 
					</view>
				</swiper-item> 
				 
			</swiper>
		</view>
		<!-- 爆单产品展示 -->
<!-- 		<view class="ft_1 items" style="height: 380rpx;">
			<view class="items_1">
				<view class="items_2"></view>
				<view class="items_3" >
					爆单区<view class="more" @click="moreGoods()" >更多<image src="/static/gengduo@3x(1).png" class="more_1"></image>
					</view>
				</view>
				<view class="items_4" v-for="service in goods" :key="service.id" @click="detail(service)">
					<view class="items_5">
						<image class="items_6" :src="service.thumbnail"></image>
						<view class="items_7">
							<view class="items_8">
								团购
							</view>
							<view class="items_9">
								<image class="shop_item10" src="/static/dingwei001.png" style="margin-top: 7rpx;"></image>{{service.juLi}}
							</view>
						</view>
					</view>
					<view class="items_10">
						{{service.name}}
					</view>
					<view class="items_11">
						<view v-for="(i,index) in 5" style="float: left;" :key="index">
							<image v-if="service.score>=i" src="../../static/ic_xing@3x(1).png" style="width: 20rpx;height: 20rpx"></image>
							<image v-if="service.score>=i-0.5&&service.score<i" src="../../static/ic_xing2@3x.png" style="width: 20rpx;height: 20rpx"></image>
							<image v-if="service.score>i-1&&service.score<i-0.5" src="../../static/ic_xing3@3x.png" style="width: 20rpx;height: 20rpx"></image>
						</view> 
						<label style="font-size: 24rpx;">{{service.score}}分</label>
					</view>   
					
					<view class="items_16" style="float: left;margin-left: 20rpx;">
						您有{{service.buyNum}}位邻居已下单
					</view>
					
					<view v-if="service.isBook==1" class="items_16" style="float: left;margin-left: 20rpx;border: none;color: #9D9D9D;text-align: center;font-size: 20rpx;">
						需要预约&nbsp;|&nbsp;交易保障
					</view>
					<view v-if="service.isBook==0" class="items_16" style="float: left;margin-left: 20rpx;border: none;color: #9D9D9D;text-align: center;font-size: 20rpx;">
						无需预约&nbsp;|&nbsp;交易保障
					</view>
					
					<view class="items_12" style="float: left;margin-left: 25rpx;line-height: 30rpx;">
						<lable class="items_13">&yen;{{service.price}}</lable>
						<lable class="items_14">&yen;{{service.originPrice}}</lable>
						<lable class="items_15">
							{{service.zheKou}}
						</lable>
					</view> 
				</view>
			</view>
		</view> -->
		<!-- 商家优选展示 -->
		<view class="ft_1 shop_item">
			<view class="shop_item_1">
				<view class="items_2"></view>
				<view class="items_3">
					商家优选<view class="more" @click="shopMore()">更多<image src="/static/gengduo@3x(1).png" class="more_1" ></image>
					</view>
				</view>
				<view v-for="shop in shops" :key="shop.id">
					<view class="shop_item1" @click="shopGoods(shop)">
						<view class="shop_item2">
							<image class="shop_item3" :src="shop.shopImage"></image>
						</view>
						<view class="shop_item4">
							<view class="shop_item5">
								{{shop.shopName}}
							</view>
							<view class="shop_item6">
								{{shop.position}}
							</view>
							<view class="shop_item7">
								{{shop.hotMessage}}
							</view>
							<view class="shop_item8">  
								{{shop.tags}}
							</view> 
						</view>
					</view>
					<view class="shop_item9">
						<image class="shop_item10" src="/static/ic_dizhi.png"></image>
						<view class="shop_item11">{{shop.juLi}}</view>
					</view>
				</view>
			</view>
		</view>
		<view class="botom">
			<view class="botom_1">杭州爱在37度网络科技有限公司</view>
			<view class="botom_2">4008009531</view>
		</view>
	</view>
</template>

<script setup> 
	let a = 0;
	let b = 3;
	let remainder = a % b;
	console.log("BBBBBBBBBBBBBBBBBBBBBBBBBB",remainder); 
	import http from "../../utils/http";
	const district = ref("未绑定");
	const menus = ref(); 
	const shareData = ref();
	
	function districtSet(){
		if(getApp().globalData.user.userId){
			http.request({
			 	url: "/home/get/userInfo",
			 	method: "POST",
			 	data: {
			 		"userId":getApp().globalData.user.userId
			 	}
			}).then((responseData) => { 
				 if(responseData.code==1){
					getApp().globalData.user=responseData.data;
					if(getApp().globalData.user.village){
						var ttt=getApp().globalData.user.village.city+"-"+getApp().globalData.user.village.name;
						if(district.value!=ttt){
							district.value=getApp().globalData.user.village.city+"-"+getApp().globalData.user.village.name; 
							goods.value=[];
							setJuLi();
						} 
					}else{
						district.value="未绑定"
					}  
				 }
				 
			}).catch((err) => { 
			 	uni.showToast({
			 		icon: 'error',
			 		title: '请求失败'
			 	})
			})
		}
	}
	function bangXiaoQu(){
		uni.navigateTo({
			url: "/pages/home/community"
		});
	} 
	const homeQuery=ref("");
	function goodsList(){
		if(homeQuery.value==""){
			uni.showToast({
				icon: 'error',
				title: '请输入商品、机构名称查询'
			});
			return;
		} 
		uni.navigateTo({
			url: "/pages/goods/shop_goods?homeQuery="+homeQuery.value
		});
	} 
	setInterval(() => { 
		districtSet();
		if(!shareData.value){
			shareData.value={
				title: '社区15分钟生活圈，生活服务邻里团购巨省钱',
				desc: '心起点数字生活',
				path: '/pages/home/home?shareId='+getApp().globalData.user.userId,
				imageUrl: 'https://love.lovein37.com/upload/application/47/1724146965750.jpg',
			}
			uni.$mpShare = shareData.value;
		} 
	},3000);
	var goods=ref([]);
	function initGoods(){
		http.request({
			url: "/home/goods",
			method: "POST",
			data: {
				pageSize:30,
				pageIndex:1,
				goods:{
					isHome:1,
					city:getApp().globalData.user.city,
					district:getApp().globalData.user.district,
				}
			}
		}).then((responseData) => {
				
			 console.log("bbbbb:",responseData.data);
			 for(var i=0;i<responseData.data.length;i++){
			 	responseData.data[i].juLi=distance(address.value.latitude, address.value.longitude, responseData.data[i].latitude,responseData.data[i].longitude);
			 	responseData.data[i].zheKou= calculateDiscount(responseData.data[i].originPrice,responseData.data[i].price) ;
				var score=responseData.data[i].score/20;
				responseData.data[i].score=score.toFixed(1);
			 }
			var obj=[];
			if(responseData.data.length<3){
				obj=responseData.data;
				goods.value.push(obj);
			}else{
				for(var i=0;i<responseData.data.length;i++){
					if(i%3==0&&obj.length>0){
						console.log(i,i%3)
						goods.value.push(obj);
						console.log("zzzzzzzzzz"+i,obj);
						obj= [];
					} 
					obj.push(responseData.data[i]);
				}
			} 
			// goods.value=responseData.data;
			 console.log("zzzzzzzzzz",goods.value)
		}).catch((err) => {
			uni.showToast({
				icon: 'error',
				title: '请求失败'
			});
			uni.hideLoading();
		}) 
	}
	
	var shops=ref([]);
	function initShops(){
		http.request({
			url: "/home/shop",
			method: "POST",
			data: {
				pageSize:10,
				pageIndex:1,
				shop:{
					city:getApp().globalData.user.city,
					district:getApp().globalData.user.district,
				}
			}
		}).then((responseData) => { 
			 for(var i=0;i<responseData.data.length;i++){
			 	responseData.data[i].juLi=distance(address.value.latitude, address.value.longitude, responseData.data[i].latitude,responseData.data[i].longitude); 
			 }
			 shops.value=responseData.data; 
			 console.log("shops.value=",shops.value)
		}).catch((err) => {
			uni.showToast({
				icon: 'error',
				title: '请求失败'
			});
			uni.hideLoading();
		}) 
	}
	
	function detail(item){
		uni.navigateTo({
			url: "/pages/goods/detail?id="+item.id
		});
	}
	function moreGoods(){ 
		uni.navigateTo({
			url: "/pages/goods/shop_goods?isHot=1"
		});
	}
	function shopMore(){
		uni.navigateTo({
			url: "/pages/home/shop"
		});
	}
	function shopGoods(item){
		uni.navigateTo({
			url: "/pages/goods/shop_goods?userId="+item.userId
		});
	}
	function initNenu(){
		console.log(getApp().globalData.user.district)
		if(getApp().globalData.user.district!=null){
			district.value=getApp().globalData.user.district;
		} 
		http.request({
			url: "/sys/menu/list",
			method: "POST",
			data: {
				isShow:null,
				pid:0
			}
		}).then((responseData) => {
			 console.log("bbbbb:",responseData.data);
			 menus.value=responseData.data;
		}).catch((err) => {
			uni.showToast({
				icon: 'error',
				title: '请求失败'
			});
			uni.hideLoading();
		})
	}
	initNenu();
	const swiper=ref();
	function initSwiper(){
		console.log(getApp().globalData.user.district)
		if(getApp().globalData.user.district!=null){
			district.value=getApp().globalData.user.district;
		} 
		http.request({
			url: "/home/swiper",
			method: "POST"
		}).then((responseData) => { 
			 swiper.value=responseData.data;
		}).catch((err) => {
			uni.showToast({
				icon: 'error',
				title: '请求失败'
			});
			uni.hideLoading();
		})
	}
	initSwiper();
	function goPage(item){
		console.log(item.url)
		if(item.url!=null){
			console.log(1)
			if(item.type==1){
				console.log(2)
				uni.navigateTo({
					url: item.url
				});
			}else{
				console.log(3)
				wx.switchTab({
				  url: item.url,
				  success: function(res) {
				    // 跳转成功
				  },
				  fail: function(err) {
				    // 错误处理
				  }
				})
			}
		}
	}
  
	const address=ref({
		longitude:0,
		latitude:0
	});
	 
	function setJuLi(){
		uni.getLocation({
			type: 'wgs84',
			success: function (res) { 
				console.log(res)
				console.log('当前位置的经度：' + res.longitude);
				console.log('当前位置的纬度：' + res.latitude);
				address.value.longitude=res.longitude;
				address.value.latitude=res.latitude;  
				initGoods();
				initShops();
			},
			fail: function(error) {
				uni.showToast({
					icon: 'error',
					title: '位置信息获取失败'
				});
				// goods.value=[];
				// shops.value=[];
				initGoods();
				initShops();
			}
		}); 
	}
	//setJuLi()
	/**折扣计算
	 * @param {Object} originalPrice 原价
	 * @param {Object} discountPrice 现价
	 */
	function calculateDiscount(originalPrice, discountPrice) {
	  if (discountPrice === 0 || originalPrice === 0) {
	    return 0; // 无折扣或原价为0时，返回0
	  }
	  const zheKou=(discountPrice / originalPrice) * 10; 
	  const length=zheKou.toString().length;
	  if(length>4){
		return zheKou.toFixed(2)+"折";
	  }
	  return zheKou+"折"; // 计算折扣力度并返回
	}
	
	function distance(la1, lo1, la2, lo2) { 
		console.log(la1+"----"+lo1+"----"+la2+"----"+lo2)
	    var La1 = la1 * Math.PI / 180.0;  
	    var La2 = la2 * Math.PI / 180.0;  
	    var La3 = La1 - La2;  
	    var Lb3 = lo1 * Math.PI / 180.0 - lo2 * Math.PI / 180.0;  
	    var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(La3 / 2), 2) + Math.cos(La1) * Math.cos(La2) * Math.pow(Math.sin(Lb3 / 2), 2)));  
	    s = s * 6378.137;//地球半径  
	    s = Math.round(s * 10000) / 10000; 
		if(s<1){
			s=s*1000;
			s= s.toFixed(2);
			s=s+"m";
		}else{
			s= s.toFixed(2);
			s=s+"km"
		} 
		return s;
	}

	const imgList = ref([
		'/static/banner.png',
		'/static/banner.png',
		'/static/banner.png'
	])
	const indicatorDots = ref(true)
	const autoplay = ref(true)
	const interval = ref(2000)
	const duration = ref(500)
	// menu跳转
	function toMenu(pageUrl){
		if(pageUrl=='中达寄件'){
			wx.navigateToMiniProgram({
				appId: 'wx756979052d2c1760',
				path: '/pages/forward/index?parentId=DDU20123903',
				extraData: {
					foo: 'bar'
				},
				envVersion: 'release',
				success(res) {
				// 打开成功
					console.log("跳转小程序成功!", res);
				}
			}); 
			return;
		}
		
		if(pageUrl.indexOf("goods/goods")==-1){
			uni.showToast({
				icon: 'error',
				title: '所在区域暂未开通此服务'
			})
			return;
		}
		uni.navigateTo({
			url:pageUrl
		})
	}
	// 获取位置授权和经纬度信息
	function getLocation() {
		uni.getLocation({
			type: "wgs84",
			success(res) {
				getApp().globalData.isGetLocation = true;
				getApp().globalData.location.latitude = res.latitude
				getApp().globalData.location.longitude = res.longitude
				console.log(getApp().globalData.location)
			},
			fail(err) {
				console.log("errLocation", err)
				getApp().globalData.isGetLocation = false;
			}

		})
	}

	function getUserInfo() {
		uni.login({
			"provider": "weixin",
			// "onlyAuthorize": true, // 微信登录仅请求授权认证
			success: function(loginRes) {
				//客户端成功获取授权临时票据（code）,向业务服务器发起登录请求。
				console.log("code", loginRes.code)
				http.request({
					url: '/api/user/get_user_info',
					method: 'POST',
					data: {
						code: loginRes.code
					}
				}).then((responseData) => {
					getApp().globalData.user = responseData.data
					if (getApp().globalData.user.phone) {
						console.log("当前用户已存在数据库中:", getApp().globalData.user)
					} else {
						console.log("当前用户不存在数据库中:", getApp().globalData.user)
						uni.showToast({
							icon: "error",
							title: "未注册",
							duration: 3000,
							complete: function() {
								// setTimeout(function() {
								// 	uni.navigateTo({
								// 		url: "/pages/login/login"
								// 	});
								// }, 1500); // 延迟1.5秒后跳转
							}
						})
					}
					console.log("global", getApp().globalData)
					//  这里应该还去判断用户的社区等信息是否存在，如果不存在可以来个提示绑定一下
				}).catch((err) => {
					// 在这里处理请求失败的情况
					console.log("err", err)
				});
			},
			fail: function(ee) {
				console.log("ee", ee)
			}
		})
	}
	// 初始加载用户信息和地理位置信息
	onMounted(() => {
		// getUserInfo(); // 页面加载时先获取一次用户信息
		// getLocation(); 
		// // 每隔一定时间获取一次用户信息
		// const userInfoInterval = setInterval(() => {
		// 	getUserInfo();
		// }, 1 * 60 * 1000); // 每 5 分钟执行一次

		// const locationInterval = setInterval(()=>{
		// 	getLocation();
		// }, 10 * 60 * 1000)
		// // 组件销毁时清除定时器
		// onUnmounted(() => {
		// 	clearInterval(userInfoInterval);
		// 	clearInterval(locationInterval);
		// });
	});
	import {
		onLoad,onShow,
		onPageScroll
	} from '@dcloudio/uni-app';
	onLoad((query) => {
		 
	})
	onShow(() => {
		//districtSet();
		setJuLi(); 
	})
</script>

<style>
	@import "./home.scss";
	.scroll-view {
	  white-space: nowrap;
	  width: 100%;
	}
</style>